package com.opensso.client.service;


import com.alibaba.fastjson.JSON;
import com.opensso.client.dao.VerifyDAO;
import com.opensso.core.enums.SessionEnum;
import com.opensso.core.tools.JwtToken;
import com.opensso.core.tools.SessionTools;
import com.opensso.core.tools.redis.RedisUtils;
import com.opensso.domain.dao.DomainPoolDAO;
import com.opensso.domain.entity.DomainPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 会话业务层
 */
@Service("verifySV")
@Slf4j
public class VerifySVImpl implements VerifySV {


    @Autowired
    private VerifyDAO verifyDAO;

    @Autowired
    private DomainPoolDAO domainPoolDAO;

    @Resource
    private RedisUtils redisUtils;


    /**
     * 验证token 合法性
     * 1.验证合法性
     * 2.记录登录系统加入注册队列
     *
     * @param token
     * @param apiKey 生成token的秘钥
     * @return true/false
     */
    @Override
    public boolean verifyToken(String token, String apiKey) {
        //1.验证合法性
        //先判断数据库apikey是否存在
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("apiKey", apiKey);
        DomainPool domainPool = domainPoolDAO.load(paraMap);
        if (domainPool == null) {
            return false;
        }
        boolean isVerify = JwtToken.verifier(token, domainPool.getApiSecret());
        if (!isVerify) {
            //验证不通过直接返回false
            return false;
        }

        String sessionKey = JwtToken.getTokenValue(token, domainPool.getApiSecret(), SessionEnum.SessionKey.name());
        if (!redisUtils.hasKey(sessionKey)) {
            //如果已经不存在sessionkey了说明已经全局注销，直接返回false
            return false;
        }

        //2.记录登录系统加入注册队列
        String regDomainPoolKey = SessionTools.Instance.genRegDomainPoolKey(sessionKey);
        List<DomainPool> domainPools = null;
        if (redisUtils.hasKey(regDomainPoolKey)) {
            String json = redisUtils.get(regDomainPoolKey).toString();
            domainPools = JSON.parseArray(json, DomainPool.class);
            domainPools.add(domainPool);
        } else {
            domainPools = new ArrayList<>();
            domainPools.add(domainPool);
        }
        //注册登录的系统
        redisUtils.set(regDomainPoolKey, JSON.toJSONString(domainPools));

        return true;
    }

}
